package org.prail.wrappers;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import org.prail.net.Configuration;
import org.prail.ui.ResultsTable;
import org.prail.utils.StringUtils;

public class SearchResult extends Thread {
	private String mp3url = null;
	private String title = null;
	private String artist = null;
	private String length = null;
	private File dir = null;

	public SearchResult(String mp3url, String title, String artist,
			String length) {
		this.mp3url = mp3url;
		this.title = title;
		this.artist = artist;
		this.length = length;
	}

	/**
	 * MP3 url
	 * 
	 * @return returns url where mp3 file can be downloaded from
	 */
	public String getMP3Url() {
		return mp3url;
	}

	/**
	 * Gets artist
	 * 
	 * @return artist of song
	 */
	public String getArtist() {
		return artist;
	}

	/**
	 * Gets title
	 * 
	 * @return title of song
	 */
	public String getTitle() {
		return title;
	}

	/**
	 * Gets length of song
	 * 
	 * @return length of song
	 */
	public String getLength() {
		return length;
	}

	@Override
	public String toString() {
		return getArtist() + " - " + getTitle() + " [" + getLength() + "] [ "
				+ getMP3Url() + " ]";
	}

	public int getBitrate() {
		HttpURLConnection conn = null;
		int bitrate = -1;
		try {
			URL url = new URL(getMP3Url());
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("HEAD");
			conn.getInputStream();
			bitrate = conn.getContentLength();
		} catch (IOException e) {
			return -1;
		} finally {
			conn.disconnect();
		}
		final String[] length = getLength().split(":");
		final int seconds = (Integer.parseInt(length[0]) * 60) + Integer.parseInt(length[1]);
		return bitrate * 8 / seconds / 1000;
	}
	
	@Override
	public void run() {
		int bitrate = getBitrate();
		ResultsTable.model.setValueAt(bitrate + "kbps", ResultsTable.getRow(this), 3);
	}

	public File getSaveFile() {
		if (dir == null) {
			dir = Configuration.saveDir;
		}
		String path = dir.getAbsolutePath() + "/";
		String fileName = StringUtils.fileName(getArtist() + " - " + getTitle()
				+ ".mp3");
		return new File(path + fileName);
	}

}
